$(function () {
  const layer = layui.layer;

  // 1.定义数据请求并渲染列表
  goodsCartList();
  function goodsCartList() {
    $.ajax({
      method: "GET",
      url: "http://124.223.14.236:3001/api/cart",
      headers: {
        Authorization: localStorage.getItem("token"),
      },
      success: function (res) {
        if (!res.success) return layer.msg("还没有加入购物车呦");
        // 判断是否有商品没有就显示“暂无信息”，否则就隐藏
        if (res.data.length === 0) {
          $("#noGoods").show();
        } else {
          $("#noGoods").hide();
        }

        let str = "";
        res.data.forEach((item) => {
          const {
            buy_num,
            cate_id,
            goods_id,
            id,
            img,
            is_selected,
            price,
            title,
            user_id,
          } = item;
          str += `
            <tr  align="center">
              <td>
                <input class="check" type="checkbox">
              </td>
              <td>${id}</td>
              <td>${title}</td>
              <td class="img">
                <img src="${img}"  style="width:70px;height:70px;" alt="">
              </td>
              <td class="price">${price.toFixed(2)}</td>
              <td class="num">
                <span class="reduce" data-id="${id}">-</span>
                <input value="${buy_num}" type="text">
                <span class="add" data-id="${id}">+</span>
              </td>
              <td class="account">${(buy_num * price).toFixed(2)}</td>
              <td>
                <button class="del"  data-id="${id}">删除</button>
              </td>
            </tr>   
          `;
        });

        $("tbody").html(str);
      },
    });
  }

  // 2.点击删除，删除商品，通过事件委托
  $("tbody").on("click", ".del", function () {
    const id = $(this).attr("data-id");
    layer.confirm("确认删除?", { icon: 3, title: "删除商品" }, function (index) {
      $.ajax({
        method: "DELETE",
        url: `http://124.223.14.236:3001/api/cart/delete/${id}`,
        headers: {
          Authorization: localStorage.getItem("token"),
        },
        success: function (res) {
          if (!res.success) return layer.msg("删除失败")
          layer.msg("删除成功")
          goodsCartList()
        },
      })

      layer.close(index);
    });
  });

  // 3.加商品
  $('body').on('click','.add',function(){
    const id = $(this).attr("data-id")
    console.log(id)
    $.ajax({
      method:'PUT',
      url:`http://124.223.14.236:3001/api/cart/update/${id}`,
      headers: {
        Authorization: localStorage.getItem("token"),
      },
      success:function(res){
        console.log(res)
        // if(!res.success) return
        // goodsCartList()
      }
    })

  })
});
